<template>
	<div id="building"></div>
	<div v-if="isReady === 1">
		<tabbar :user="user" @signOut="singOut"></tabbar>
		<router-view @login="login" :user="user" :userList="userList"></router-view>
	</div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import tabbar from './components/tabbar.vue';
import { ElMessage } from 'element-plus';
const user = ref({
	uid: 0,
	img: '/zzzLogo.png',
	userName: '未登录'
})
const userList = ref(new Map())
const isReady = ref(0)
onMounted( () => {
	// 发送token到后端，检查是否过期，获得登录用户信息
	// 获取用户列表并转为map方便查找
	axios.get('/api/users')
		.then(res => {
			for(let i = 0 ;i<res.data.data.length;i++) {
				let el = res.data.data[i]
				if (el.img === "") {
					el.img = '/zzz.jpg'
				}
				userList.value.set(el.uid, el)
			}
		}).catch(e => {
			ElMessage({
				message:e,
				type:"error"
			})
		})
})
onMounted(()=>{
	getUserInformation(isReady)
})

const login = function() {
	getUserInformation(null)
}

const getUserInformation = async function(temp) {
	let token = localStorage.getItem('token')
	if (token === null) {
		isReady.value ++
		return
	}
	await axios.get(`/api/users/${token}`)
	.then(res => {
		if (res.data.code === 0) {
			localStorage.removeItem('token')
		} else
		user.value = res.data.data
		if (user.value.img === "") user.value.img = '/zzzLogo.png'
		if(temp!==null) {
			temp.value++
		}
	}).catch(e => {
			ElMessage({
				message:e,
				type:"error"
			})
	})
}

const singOut = function () {
	ElMessage({
		message: "退出登录",
		offset: 100,
		type: 'success'
	})
	localStorage.removeItem('token')
	user.value = {
		img: '/public/zzzLogo.png',
		userName: '未登录'
	}
	location.reload()
}
</script>

<style>

#building {
	position: absolute;
	z-index: -1;
    /*兼容浏览器版本*/
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
    -webkit-background-size: cover;
    -o-background-size: cover;                
    background-size: cover;
    object-fit: fill;
    background-size: 100%;
    background: url(/fill-black-right.png)  center center fixed;
    background-color: #333;
}

</style>